<template>
    <div>
        <h2>{{ form?.last_name }} {{ form?.first_name }}</h2>

        <div class="collapsible-actions">
            <el-button link @click="toggleCollapseAll">
                <el-icon size="16" color="#4c4c4c"><CaretBottom /></el-icon>
                {{ $t(btnText) }}
            </el-button>
        </div>
        <el-form :model="form" label-width="25%" label-position="left" v-if="form" v-loading="loading">
            <el-collapse v-model="collapseName">
                <el-collapse-item :title="$t('user.edit.collapse.general')" name="一般">
                    <el-form-item size="large" :label="$t('user.edit.last_name')">
                        <el-input v-model="form.last_name" disabled />
                    </el-form-item>
                    <el-form-item size="large" :label="$t('user.edit.first_name')">
                        <el-input v-model="form.first_name" disabled />
                    </el-form-item>
                    <el-form-item size="large" :label="$t('user.edit.email')">
                        <el-input v-model="form.email" disabled />
                    </el-form-item>
                    <!-- <el-form-item size="large">
                        <template #label>
                            {{ $t('user.edit.show_email_type') }}
                            <el-tooltip class="box-item" effect="dark" :content="$t('user.edit.show_email_type_tip')" placement="right">
                                <el-icon size="16" color="#1C77C3"><QuestionFilled /></el-icon>
                            </el-tooltip>
                        </template>
                        <el-select v-model="form.show_email_type">
                            <el-option :label="$t('user.edit.show_email_type_opt_2')" :value="2" />
                            <el-option :label="$t('user.edit.show_email_type_opt_1')" :value="1" />
                            <el-option :label="$t('user.edit.show_email_type_opt_3')" :value="3" />
                        </el-select>
                    </el-form-item> -->
                    <el-form-item size="large">
                        <template #label>
                            {{ $t('user.edit.moodlenet_account') }}
                            <el-tooltip class="box-item" effect="dark" :content="$t('user.edit.moodlenet_account_tip')" placement="right">
                                <el-icon size="16" color="#1C77C3"><QuestionFilled /></el-icon>
                            </el-tooltip>
                        </template>
                        <el-input v-model="form.moodlenet_account" />
                    </el-form-item>
                    <el-form-item size="large" :label="$t('user.edit.city_address')">
                        <el-input v-model="form.city_address" />
                    </el-form-item>
                    <el-form-item size="large" :label="$t('user.edit.country')">
                        <el-select v-model="form.country" filterable :placeholder="$t('user.edit.country_placeholder')">
                            <el-option v-for="country in countries" :label="country.name" :value="country.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item size="large" :label="$t('user.edit.timezone')">
                        <el-select v-model="form.timezone" filterable :placeholder="$t('user.edit.timezone_placeholder')">
                            <el-option v-for="time in timezone" :label="time.name" :value="time.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item size="large" :label="$t('user.edit.introduction')">
                        <RichTextEditor v-model="form.introduction" @update-richValue="form.introduction = $event" />
                    </el-form-item>
                </el-collapse-item>
                <el-collapse-item :title="$t('user.edit.collapse.avatar')" name="用戶的相片">
                    <el-form-item size="large" :label="$t('user.edit.avatar')">
                        <el-upload :show-file-list="false" :before-upload="beforeAvatarUpload" accept="image/jpeg, image/png" :http-request="handleUpload">
                            <div class="user-picture">
                                <div class="pic" v-if="form?.avatar_url">
                                    <img :src="form.avatar_url" class="ele" />
                                </div>
                                <el-icon v-else size="35" color="#8d8d8d"><Plus /></el-icon>
                            </div>
                            <template #tip>
                                <div class="el-upload__tip">
                                    <p>{{ $t('user.edit.avatar_tip_1') }}</p>
                                    <p>{{ $t('user.edit.avatar_tip_2') }}</p>
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                    <el-form-item size="large" :label="$t('user.edit.avatar_description')">
                        <el-input v-model="form.avatar_description" />
                    </el-form-item>
                </el-collapse-item>
                <!-- <el-collapse-item :title="$t('user.edit.collapse.additional')" name="附加名稱">
                    <el-form-item size="large" :label="$t('user.edit.additional_first_name')">
                        <el-input v-model="form.additional_first_name" />
                    </el-form-item>
                    <el-form-item size="large" :label="$t('user.edit.additional_last_name')">
                        <el-input v-model="form.additional_last_name" />
                    </el-form-item>
                    <el-form-item size="large" :label="$t('user.edit.additional_middle_name')">
                        <el-input v-model="form.additional_middle_name" />
                    </el-form-item>
                    <el-form-item size="large" :label="$t('user.edit.additional_alias')">
                        <el-input v-model="form.additional_alias" />
                    </el-form-item>
                </el-collapse-item> -->
                <el-collapse-item :title="$t('user.edit.collapse.interests')" name="興趣">
                    <el-form-item size="large" :label="$t('user.edit.interests')">
                        <el-input-tag v-model="form.interests" :placeholder="$t('user.edit.interests_placeholder')" />
                    </el-form-item>
                </el-collapse-item>
                <el-collapse-item :title="$t('user.edit.collapse.selected')" name="選擇的">
                    <el-form-item size="large" :label="$t('user.edit.code')">
                        <el-input v-model="form.code" disabled />
                    </el-form-item>
                    <el-form-item size="large" :label="$t('user.edit.institution')">
                        <el-input v-model="form.institution" disabled />
                    </el-form-item>
                    <el-form-item size="large" :label="$t('user.edit.department')">
                        <el-input v-model="form.department" />
                    </el-form-item>
                    <el-form-item size="large" :label="$t('user.edit.phone_number')">
                        <el-input v-model="form.phone_number" />
                    </el-form-item>
                    <el-form-item size="large" :label="$t('user.edit.mobile_number')">
                        <el-input v-model="form.mobile_number" />
                    </el-form-item>
                    <el-form-item size="large" :label="$t('user.edit.detailed_address')">
                        <el-input v-model="form.detailed_address" />
                    </el-form-item>
                </el-collapse-item>
            </el-collapse>

            <div class="btn-list">
                <el-button @click="submitHandle" color="#F06423">{{ $t('user.edit.btn_update') }}</el-button>
                <el-button @click="cancleHandle" color="#F06423">{{ $t('golbal.btn_text_3') }}</el-button>
            </div>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, type UploadRequestOptions } from 'element-plus'
import { useI18n } from 'vue-i18n'

import { useUserStore } from '@/stores/user'
import type { UserInfo } from '@/types/user'
import UserService from '@/api/user'

import RichTextEditor from '@/components/RichTextEditor.vue'

import ResourceService from '@/api/resource'

import { countries } from '@/utils/constants'
import { timezone } from '@/utils/timezone'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const userId = computed(() => Number(route.query.userId)) // 如果是当前登录用户，则没有userId

const collapseName = ref(['一般'])
const form = ref<UserInfo>()
const { t } = useI18n<{ message: MessageSchema }, SupportedLocales>()

function getUserInfo() {
    UserService.getById(userId.value).then(res => {
        form.value = res
    })
}
const submitHandle = () => {
    if (!form.value) return
    loading.value = true
    UserService.update(form.value).finally(() => {
        loading.value = false
    })
}
const cancleHandle = () => {
    router.go(-1)
}

const btnText = computed(() => {
    if (collapseName.value.length !== 5) {
        return 'user.edit.expand_all'
    } else {
        return 'user.edit.collapse_all'
    }
})
const toggleCollapseAll = () => {
    if (collapseName.value.length !== 5) {
        collapseName.value = ['一般', '用戶的相片', '附加名稱', '興趣', '選擇的']
    } else {
        collapseName.value = []
    }
}

// 上传
const beforeAvatarUpload = (file: File) => {
    const validTypes = ['image/jpeg', 'image/png']
    const isImage = validTypes.includes(file.type)
    const isLt500M = file.size / 1024 / 1024 < 500

    if (!isImage) {
        ElMessage.error(t('golbal.upload_err_5', 'JPG/PNG/GIF/WEBP'))
        return false
    }
    if (!isLt500M) {
        ElMessage.error(`${t('golbal.upload_err_1')} 500MB!`)
        return false
    }
    return true
}
const handleUpload = (options: UploadRequestOptions) => {
    loading.value = true
    const { file } = options
    const formData = new FormData()
    formData.append('file', file)
    formData.append('type', 'image')
    formData.append('filename', file.name)
    ResourceService.upload(formData)
        .then(res => {
            if (form.value) form.value.avatar_url = res.url
        })
        .finally(() => {
            loading.value = false
        })
}

watch(
    () => route.fullPath,
    () => {
        if (userStore.userinfoL && !userId.value) {
            form.value = {
                ...userStore.userinfoL,
            }
        } else {
            getUserInfo()
        }
    },
)

onMounted(() => {
    if (userStore.userinfoL && !userId.value) {
        form.value = {
            ...userStore.userinfoL,
        }
    } else {
        getUserInfo()
    }
})
</script>

<style lang="less" scoped>
h2 {
    margin-bottom: 30px;
    font-size: 30px;
    font-weight: normal;
    line-height: 1.2;
    color: #000;
}

.collapsible-actions {
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-end;
}

:deep(.el-collapse) {
    border: none;
    --el-collapse-header-bg-color: #efefef;
    --el-collapse-header-text-color: ;
    --el-collapse-header-font-size: 15px;

    .el-collapse-item {
        margin-bottom: 12px;

        .el-collapse-item__header {
            border: none;
            border-left: 2px solid #f06423;
            padding: 0 15px;
            font-weight: normal;
        }

        .el-collapse-item__wrap {
            border: 1px solid #ebebeb;
            padding: 15px 15px 0;

            .el-collapse-item__content {
                padding-bottom: 0;
            }
        }
    }
}

:deep(.el-form) {
    .el-form-item {
        .el-form-item__label {
            align-items: center;
            justify-content: space-between;

            color: #4c4c4c;
        }

        .el-input-name {
            border-radius: 4px;
            box-shadow: 0 0 0 1px #e4e7ed inset;
            padding: 0 11px;
            line-height: 32px;
            background-color: #f5f7fa;
            color: #a8abb2;
            cursor: not-allowed;
            width: 100%;
        }
    }

    .btn-list {
        display: flex;
        justify-content: center;
    }
}

:deep(.ck-editor) {
    width: 100%;

    .ck-editor__main {
        .ck-content {
            min-height: 350px;
            max-height: 600px;
        }
    }
}

.user-picture {
    border: 1px solid #ebebeb;
    width: 80px;
    height: 80px;

    display: flex;
    align-items: center;
    justify-content: center;

    .pic {
        width: 100%;
    }
}

.el-upload__tip {
    margin-top: 15px;
    line-height: 1.2;
}
</style>
